package com.yueyi.gulimall.product.service.impl;

import com.yueyi.gulimall.product.vo.Catelog2Vo;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueyi.common.utils.PageUtils;
import com.yueyi.common.utils.Query;

import com.yueyi.gulimall.product.dao.CategoryDao;
import com.yueyi.gulimall.product.entity.CategoryEntity;
import com.yueyi.gulimall.product.service.CategoryService;

import static com.google.common.graph.ElementOrder.sorted;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).
                map(categoryEntity -> {categoryEntity.setChildren(getChildrens(categoryEntity,categoryEntities)); return categoryEntity;}).
                sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());


        return level1Menus;
    }

    public List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> categoryEntities){
        List<CategoryEntity> children = categoryEntities.stream().filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), root.getCatId()))
                .map(categoryEntity -> {categoryEntity.setChildren(getChildrens(categoryEntity,categoryEntities)); return categoryEntity;})
                .sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }

}